import config from '../../config.js'
function webSocket (onsuccess) {
  this.wsUrl = config.wssUrl
  this.lockReconnect = false
  this.createWebSocket()
  this.success = onsuccess
}
webSocket.prototype.createWebSocket = function (type) {
  this.ws = uni.connectSocket({
		url: this.wsUrl,
		success: function(res) {
			// 链接成功
		}
	})
  this.init(type)
}
webSocket.prototype.init = function (type) {
	// console.log('创建链接')
	this.ws.onOpen(res => {
		// console.log('链接打开')
		this.success(type)
	})
	this.ws.onClose(res => {
		// console.log('链接关闭')
		this.reconnect(101)
	})
	this.ws.onError(res => {
		// console.log('发生异常了')
		this.reconnect(101)
	})
	this.ws.onMessage(data => {
		data = JSON.parse(data.data)
		this.onmsg && this.onmsg(data.event, data.data)
	})
}
webSocket.prototype.reconnect = function reconnect (type) {
  var _this = this
  if (_this.lockReconnect) {
    return
  }
  _this.lockReconnect = true
  // 没连接上会一直重连，设置延迟避免请求过多
  let tt
  tt && clearTimeout(tt)
  tt = setTimeout(function () {
    _this.createWebSocket(type)
    _this.lockReconnect = false
  }, 4000)
}
webSocket.prototype.emit = function (eventName, data) {
  this.ws.send({
		data: JSON.stringify({
			event: eventName,
			data: data
		})
	})
}
export default webSocket
// export default {}